import store from '@/store';
import config from '@/config';
import { getAccessToken, getTenantId, getRefreshToken } from '@/utils/auth';
import { refreshTokenNew } from '@/api/system/user';
import errorCode from '@/utils/errorCode';
import { toast, showConfirm, tansParams } from '@/utils/common';

let timeout = 10000;
const baseUrl = config.baseUrl;
const baseUrlFy = config.baseUrlFy;
const request = (config) => {
  if (config.url.indexOf('system/auth/logout') != -1) {
    uni.reLaunch({
      url: '/packageB/pages/login'
    });
    return;
  }
  // 只要是用用户名去换取租户接口，则去掉tenantid 和 accessToken
  if (
    config.url.indexOf('/system/tenant/get-id-by-username') == -1 &&
    config.url.indexOf('/system/auth/login') == -1
  ) {
    if (!getAccessToken()) {
      uni.reLaunch({
        url: '/packageB/pages/login'
      });
      return;
    }
  }
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getAccessToken()) {
    config.header['Authorization'] = 'Bearer ' + getAccessToken();
  }
  // 设置租户 TODO 芋艿：强制 1 先
  config.header['tenant-id'] = getTenantId();
  // get请求映射params参数
  if (config.params) {
    let url = config.url + '?' + tansParams(config.params);
    url = url.slice(0, -1);
    config.url = url;
  }
  if (config.url.indexOf('/system/auth/login') != -1) {
    config.header = {
      'tenant-id': getTenantId()
    };
  }
  // 只要是用用户名去换取租户接口，则去掉tenantid 和 accessToken
  if (config.url.indexOf('/system/tenant/get-id-by-username') != -1) {
    config.header = {};
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: config.baseUrl || baseUrl + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      })
      .then((response) => {
        const [error, res] = response;
        if (!!error) {
          // ERROR 输出准确
          toast(`网络异常`);
          reject('后端接口连接异常');
        }
        if (!res) {
          reject('网络异常');
          return;
        }
        const code = res.data.code;
        const msg = errorCode[code] || res.data.msg || errorCode['default'];
        if (code == 0) {
          resolve(res.data);
        } else {
          if (
            config.url.indexOf('queue/cust-mgr/report-energy') != -1 ||
            config.url.indexOf('queue/supplier-product/report-energy') != -1
          ) {
            reject('');
            return;
          }
          if (code == 401) {
            showConfirm(
              '登录状态已过期，您可以继续留在该页面，或者重新登录?'
            ).then((res) => {
              if (res.confirm) {
                store.dispatch('LogOut').then((res) => {
                  uni.reLaunch({
                    url: '/packageB/pages/login'
                  });
                });
              }
            });
            reject('无效的会话，或者会话已过期，请重新登录。');
            return;
          } else {
            //令牌过期&&接口是换取新令牌的
            if (
              code == 400 &&
              config.url.indexOf('/system/auth/refresh-token') != -1
            ) {
              // showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
              uni.reLaunch({
                url: '/packageB/pages/login'
              });
              reject('无效的会话，或者会话已过期，请重新登录。');
            } else if (code == 1000) {
              resolve(res.data);
            } else {
              // TODO 处理异常保存
              toast(msg);
              resolve(res.data);
            }
          }
        }
      })
      .catch((error) => {
        let { message } = error;
        // TODO 调整message字段
        if (message === 'Network Error') {
          message = '网络连接异常';
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常';
        }
        toast(message);
        reject(error);
      });
  });
};

const requestFy = (config) => {
  // 是否需要设置 token
  const isToken = (config.headers || {}).isToken === false;
  config.header = config.header || {};
  if (getAccessToken()) {
    config.header['Authorization'] = 'Bearer ' + getAccessToken();
  }
  return new Promise((resolve, reject) => {
    uni
      .request({
        method: config.method || 'get',
        timeout: config.timeout || timeout,
        url: baseUrlFy + config.url,
        data: config.data,
        header: config.header,
        dataType: 'json'
      })
      .then((response) => {
        const [error, res] = response;
        if (!!error) {
          // ERROR 输出准确
          toast(`网络异常`);
          reject('后端接口连接异常');
        }
        if (!res) {
          reject('网络异常');
          return;
        }
        const code = res.data.code;
        if (code == '-1') {
          //查询用户权限的接口getUserAuthority会出现用户信息不存在的场景
          uni.reLaunch({
            url: '/packageB/pages/login'
          });
          reject('用户信息不存在，请重新登录。');
        }
        const msg = errorCode[code] || res.data.msg || errorCode['default'];
        if (code != 0) {
          console.log('报错接口地址的信息是====：', msg);
        }
        const refreshTok = getRefreshToken();

        if (code == 0) {
          resolve(res.data);
        } else {
          //令牌过期&&接口是换取新令牌的
          if (
            code == 400 &&
            config.url.indexOf('/system/auth/refresh-token') != -1
          ) {
            // showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(res => {
            uni.reLaunch({
              url: '/packageB/pages/login'
            });
            reject('无效的会话，或者会话已过期，请重新登录。');
          }

          if (code == 401) {
            //token过期
            if (!getRefreshToken()) {
              //refreshtoken过期后才提示用户去登录
              showConfirm(
                '登录状态已过期，您可以继续留在该页面，或者重新登录?'
              ).then((res) => {
                if (res.confirm) {
                  uni.reLaunch({
                    url: '/packageB/pages/login'
                  });
                }
              });
              reject('无效的会话，或者会话已过期，请重新登录。');
            } else {
              //保存路由
              if (config.url.indexOf('/system/auth/refresh-token') == -1) {
                let routes = getCurrentPages();
                let curRoute = routes[routes.length - 1].route;
                let pageOp = routes[routes.length - 1].options;
                uni.setStorageSync('CUR_ROUTE', curRoute);
              }
              refreshTokenNew(refreshTok).then((res) => {
                if (res.code == 0) {
                  uni.setStorageSync('ACCESS_TOKEN', res.data.accessToken);
                  uni.setStorageSync('REFRESH_TOKEN', res.data.refreshToken);
                  if (res.code == 0) {
                    uni.reLaunch({
                      url: '/' + getCurRoute()
                    });
                    return;
                  }
                } else {
                  //换令牌失败后只能提示用户去登录
                  showConfirm(
                    '登录状态已过期，您可以继续留在该页面，或者重新登录?'
                  ).then((res) => {
                    if (res.confirm) {
                      store.dispatch('LogOut').then((res) => {
                        uni.reLaunch({
                          url: '/packageB/pages/login'
                        });
                      });
                    }
                  });
                  reject('无效的会话，或者会话已过期，请重新登录。');
                }
              });
            }
          } else {
            // TODO 处理异常保存
            if (code == 403) {
              //越权访问出现403，重新登录
              uni.reLaunch({
                url: '/packageB/pages/login'
              });
            } else {
              if (code == 1002015002) {
                uni.reLaunch({
                  url: '/pages/error?mess=' + msg
                });
                toast(msg);
                reject(msg);
              } else {
                //图片识别异常
                // if(config.url.indexOf('/queue/ocr/idcard-recognize') != -1 ||
                // config.url.indexOf('queue/ocr/vehicle-recognize') != -1){
                // 	resolve(res.data)
                // }
                resolve(res.data);
              }
            }
          }
        }
      })
      .catch((error) => {
        let { message } = error;
        if (message === 'Network Error') {
          message = '网络连接异常';
        } else if (message.includes('timeout')) {
          message = '系统接口请求超时';
        } else if (message.includes('Request failed with status code')) {
          message = '系统接口' + message.substr(message.length - 3) + '异常';
        }
        toast(message);
        reject(error);
      });
  });
};
export { request, requestFy };
